<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Wechat;
use app\common\model\Goods as ModelGoods;

/**
 * 商品接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * @Author LK
     * @ApiTitle (商品列表)
     * @ApiMethod (GET)
     * @ApiParams (name="keywords", type="string", required=true, sample="", description="关键字")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function index()
    {
        $param = request()->param();
        extract($param);
        $model = new ModelGoods();
        if (isset($keywords) && $keywords) {
            $model->whereLike('title', '%' . $keywords . '%');
        }
        $list = $model->order('id desc')->paginate();
        $this->success('请求成功', $list);
    }

    /**
     * @Author LK
     * @ApiTitle (商品详情)
     * @ApiMethod (get)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function info()
    {
        $param = request()->param();
        extract($param);
        $info = ModelGoods::withCount(['review'])->find($id);
        $this->success('请求成功', $info);
    }

    /**
     * @Author LK
     * @ApiTitle (生成分享码)
     * @ApiMethod (get)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="url", type="string", required=true, sample="", description="分享地址")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function goods_share()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;
        $wechat = new Wechat('wxMiniProgram');
        $scene = 'id=' . $id . '&pid=' . $this->auth->id;
        $response = $wechat->app_code($scene, [
            'page'  => $url,
            'width' => 600,
            'check_path' => false
        ]);
        $save_dir = 'path';
        $filename = 'goods_' . $id . '_' . $uid . '.png';
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs($save_dir, $filename);
        }
        $this->success('', cdnurl(DS . $save_dir . DS . $filename, true));
        // $res = $response->getBody()->getContents(); //获取图片二进制流

        // echo "<img src='{$res}'  />";

        // if (!is_array($res)) {
        //     $file =  self::saveTempImageByContent($response);
        //     if (!file_exists($file)) {
        //         exception('二维码保存失败:' . $file);
        //     }
        //     $user->qr_image = '/' . $file;
        // } else {
        //     exception('失败:' . $res['errmsg']);
        // }
    }
}
